#include <iostream>
#include <string>
#include <random>
#include <ctime>
#include <algorithm>
std::string generatePassword() {
    const char* const numbers = "0123456789";
    const char* const upperchar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const char* const lowechar = "abcdefghijklmnopqrstuvwxyz";
    const char* const specials = "!@#$%^&*()-_=+[]{}|;:,.<>?";
    const int numChars = 8; // 密码长度

    std::string password;
    std::random_device rd;
    std::mt19937 generator(rd());
    std::uniform_int_distribution<> dis;

    // 初始化密码，确保包含至少一个数字、一个大写字母、一个小写字母和一个特殊字符
    password += numbers[dis(generator) % 10];
    password += upperchar[dis(generator) % 26];
    password += lowechar[dis(generator) % 26];
    password += specials[dis(generator) % 32];

    // 填充剩余的字符
    for (int i = 4; i < numChars; ++i) {
        std::string allChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()-_=+[]{}|;:,.<>?";
        dis = std::uniform_int_distribution<>(0, allChars.size() - 1);
        password += allChars[dis(generator)];
    }

    // 打乱密码中的字符顺序，以确保随机性
    std::shuffle(password.begin(), password.end(), generator);

    return password;
}
bool isPasswordValid(const std::string& password) {
    if (password.length() != 8) {
        return false;
    }

    bool hasDigit = false;
    bool hasUpper = false;
    bool hasLower = false;
    bool hasSpecial = false;

    const std::string specials = "!@#$%^&*()-_=+[]{}|;:,.<>?";

    for (char ch : password) {
        if (isdigit(ch)) {
            hasDigit = true;
        } else if (isupper(ch)) {
            hasUpper = true;
        } else if (islower(ch)) {
            hasLower = true;
        } else if (specials.find(ch) != std::string::npos) {
            hasSpecial = true;
        }

        if (hasDigit && hasUpper && hasLower && hasSpecial) {
            return true;
        }
    }

    return hasDigit && hasUpper && hasLower && hasSpecial;
}

int main() {
    std::string userPassWord = "";
    //rootPassWord
    std::string rootPassWord = generatePassword();
    std::cout << "Generated Password :" << rootPassWord << std::endl;
    //userPassWord
    for (;;)
    {
        std::cout << "Please cin userPassWord :";
        std::cin >> userPassWord;
        // function for judging
        if (isPasswordValid(userPassWord))
        {
            // reWrite rootPassWord
            rootPassWord = userPassWord;
            std::cout << "right passWord!!!" << std::endl;
            std::cout << "rootPassWord :" << rootPassWord << std::endl;
            break;
        }else{
            std::cout << "out of valid!!!" <<  std::endl;
        }
    }

    return 0;
}